<template>
  <div id="container" style="padding: 10px; box-sizing: border-box">
    <div id="main" style="width: 100%; position: relative" v-if="show">
      <template v-for="(pageGoods, pageGoodsIndex) in order_list">
        <div
          :key="'pageGoods' + pageGoodsIndex"
          style="width: 100%; position: relative"
        >
          <!-- 标题 -->
          <div
            v-if="tem_id == 9 && print_settings.fontset"
            class="header"
            style="height: 30px; lineheight: 30px"
            :style="{
              fontSize: print_settings.fontset.fontSize + 'px',
              fontWeight: print_settings.fontset.bold ? 'bold' : 'none',
              textDecoration: print_settings.fontset.underline
                ? 'underline'
                : 'none',
              fontStyle: print_settings.fontset.italic ? 'italic' : 'none',
              textAlign: print_settings.fontset.textAlign,
            }"
          >
            {{ print_settings.page.headerTitle || "" }}
          </div>

          <div
            v-else
            class="header"
            style="font-size: 30px; height: 30px; lineheight: 30px"
            :style="{ textAlign: a }"
          >
            {{ print_settings.page.headerTitle || "" }}
          </div>

          <div style="clear: both"></div>
          <!-- 订单信息 -->
          <div style="width: 100%; position: absolute">
            <span
              v-for="(item, index) in main_settings.orderSetData.orderlist"
              :key="index"
              style="position: absolute; z-index: 1"
              :style="{
                left: item.left + 'px',
                top: item.top + 'px',
                fontSize: main_settings.orderSetData.fontset.fontSize + 'px',
                fontWeight: main_settings.orderSetData.fontset.bold
                  ? 'bold'
                  : 'none',
                textDecoration: main_settings.orderSetData.fontset.underline
                  ? 'underline'
                  : 'none',
                fontStyle: main_settings.orderSetData.fontset.italic
                  ? 'italic'
                  : 'none',
              }"
            >
              <!-- <div
                v-if="
                  item.label == '收货信息' &&
                    print_settings.printSetting.isLeftTurn90 == true
                "
              >
                <div>{{ item.label }}:</div>
                <div>{{ order[`${item.index - 1}`] }}</div>
              </div>

              <div v-else>
                {{ item.label }}:{{ order[`${item.index - 1}`] }}
              </div> -->
              <template v-if="item.label == '二维码'">
                <div
                  id="qrcode"
                  style="position: absolute; right: -70px; bottom: -70px"
                ></div>
              </template>
              <template v-else>
                {{ item.label }}{{ item.id ? "" : ":"
                }}{{ order[`${item.index - 1}`] }}
              </template>

              <!-- {{ item.label }}{{ item.id ? "" : ":"
              }}{{ order[`${item.index - 1}`] }} -->
            </span>
          </div>

          <div style="clear: both"></div>
          <!-- 配送单商品信息 -->

          <div
            class="goods"
            style="width: 100%; margin: 0; padding: 0; position: relative"
            :style="{
              marginTop:
                main_settings.mainSetData.mainlist.goodslist.top + 'px',
            }"
            v-if="
              print_document_type == 'order' &&
              print_settings.printSetting.is_category
            "
          >
            <!-- 分类 -->
            <table
              style="
                margin: 0;
                margin-bottom: 6px;
                padding: 0;
                border-collapse: collapse;
                border-spacing: 0;
                border: 1px solid #000;
                border-bottom: 0;
              "
            >
              <tbody>
                <tr
                  style="height: 25px; line-height: 25px"
                  :style="{
                    fontSize:
                      main_settings.goodsSetData.fontset.fontSize + 'px',
                    fontWeight: main_settings.goodsSetData.fontset.bold
                      ? 'bold'
                      : 'none',
                    textDecoration: main_settings.goodsSetData.fontset.underline
                      ? 'underline'
                      : 'none',
                    fontStyle: main_settings.goodsSetData.fontset.italic
                      ? 'italic'
                      : 'none',
                    textAlign: main_settings.goodsSetData.fontset.textAlign,
                  }"
                >
                  <td style="border: 1px solid #000; padding: 0 5px">类别</td>
                  <td
                    v-for="(item, index) in category_list"
                    :key="index"
                    style="border: 1px solid #000; padding: 0 5px"
                  >
                    {{ item.category_name }}
                  </td>
                </tr>
                <tr
                  style="height: 25px; line-height: 1.5"
                  :style="{
                    fontSize:
                      main_settings.goodsSetData.fontset.fontSize + 'px',
                    fontWeight: main_settings.goodsSetData.fontset.bold
                      ? 'bold'
                      : 'none',
                    textDecoration: main_settings.goodsSetData.fontset.underline
                      ? 'underline'
                      : 'none',
                    fontStyle: main_settings.goodsSetData.fontset.italic
                      ? 'italic'
                      : 'none',
                    textAlign: main_settings.goodsSetData.fontset.textAlign,
                  }"
                >
                  <td style="border: 1px solid #000; padding: 0 5px">商品数</td>
                  <td
                    v-for="(item, index) in category_list"
                    :key="index"
                    style="border: 1px solid #000; padding: 0 5px"
                  >
                    {{ item.class }}
                  </td>
                </tr>
              </tbody>
            </table>

            <!-- 商品 -->
            <table
              style="
                width: 100%;
                margin: 0;
                padding: 0;
                border-collapse: collapse;
                border-spacing: 0;
                border: 1px solid #000;
                border-bottom: 0;
              "
            >
              <tbody>
                <tr
                  style="height: 25px; line-height: 25px"
                  :style="{
                    fontSize:
                      main_settings.goodsSetData.fontset.fontSize + 'px',
                    fontWeight: main_settings.goodsSetData.fontset.bold
                      ? 'bold'
                      : 'none',
                    textDecoration: main_settings.goodsSetData.fontset.underline
                      ? 'underline'
                      : 'none',
                    fontStyle: main_settings.goodsSetData.fontset.italic
                      ? 'italic'
                      : 'none',
                    textAlign: main_settings.goodsSetData.fontset.textAlign,
                  }"
                >
                  <td
                    v-for="(item, index) in main_settings.goodsSetData
                      .goodslist"
                    :key="index"
                    :width="item.percent + '%'"
                    style="border: 1px solid #000"
                  >
                    {{ item.label }}
                  </td>
                </tr>
                <template v-for="(goods, index) in pageGoods">
                  <template v-if="democc(goods)">
                    <tr
                      :key="index"
                      style="text-align: left; line-height: 1.5"
                      :style="{
                        fontSize:
                          main_settings.goodsSetData.fontset.fontSize + 'px',
                        fontWeight: main_settings.goodsSetData.fontset.bold
                          ? 'bold'
                          : 'none',
                        textDecoration: main_settings.goodsSetData.fontset
                          .underline
                          ? 'underline'
                          : 'none',
                        fontStyle: main_settings.goodsSetData.fontset.italic
                          ? 'italic'
                          : 'none',
                        textAlign: main_settings.goodsSetData.fontset.textAlign,
                      }"
                    >
                      <td
                        v-for="(father, index) in main_settings.goodsSetData
                          .goodslist"
                        :key="index"
                        style="border: 1px solid #000; border-top: 0"
                      >
                        {{ goods[`${father.index - 1}`] }}
                      </td>
                    </tr>
                  </template>

                  <template v-else>
                    <tr
                      style="text-align: left; line-height: 1.5"
                      :key="index"
                      :style="{
                        fontSize:
                          main_settings.goodsSetData.fontset.fontSize + 'px',
                        fontWeight: main_settings.goodsSetData.fontset.bold
                          ? 'bold'
                          : 'none',
                        textDecoration: main_settings.goodsSetData.fontset
                          .underline
                          ? 'underline'
                          : 'none',
                        fontStyle: main_settings.goodsSetData.fontset.italic
                          ? 'italic'
                          : 'none',
                      }"
                    >
                      <td
                        style="
                          border: 1px solid #000;
                          border-top: 0;
                          padding-left: 15px;
                        "
                        colspan="30"
                      >
                        {{ goods.category_name }}小计：{{ goods.money }}
                      </td>
                    </tr>
                  </template>
                </template>
              </tbody>
            </table>
          </div>

          <!-- 除配送单外的商品信息 -->
          <div
            class="goods"
            style="width: 100%; margin: 0; padding: 0"
            :style="{
              marginTop:
                main_settings.mainSetData.mainlist.goodslist.top + 'px',
            }"
            v-else
          >
            <table
              style="
                width: 100%;
                margin: 0;
                padding: 0;
                border-collapse: collapse;
                border-spacing: 0;
                border: 1px solid #000;
                border-bottom: 0;
              "
            >
              <tbody>
                <tr
                  style="height: 25px; line-height: 25px"
                  :style="{
                    fontSize:
                      main_settings.goodsSetData.fontset.fontSize + 'px',
                    fontWeight: main_settings.goodsSetData.fontset.bold
                      ? 'bold'
                      : 'none',
                    textDecoration: main_settings.goodsSetData.fontset.underline
                      ? 'underline'
                      : 'none',
                    fontStyle: main_settings.goodsSetData.fontset.italic
                      ? 'italic'
                      : 'none',
                    textAlign: main_settings.goodsSetData.fontset.textAlign,
                  }"
                >
                  <div
                    v-if="
                      tem_id == 9 &&
                      print_settings.printSetting.doublePrinting == 1
                    "
                  >
                    <td
                      v-for="(two, oindex) in newtablist"
                      :key="oindex"
                      style="border: 1px solid #000"
                    >
                      {{ two.label=="产地" ? "生产厂家" : two.label }}
                    </td>
                    <td
                      v-for="(two, oindex) in newtablist"
                      :key="oindex + '1'"
                      style="border: 1px solid #000"
                    >
                      {{ two.label=="产地" ? "生产厂家" : two.label }}
                    </td>
                  </div>

                  <div v-else>
                    <td
                      :width="one.percent + '%'"
                      v-for="(one, oindex) in main_settings.goodsSetData
                        .goodslist"
                      :key="oindex"
                      style="border: 1px solid #000"
                    >
                      {{ one.label=="产地" ? "生产厂家" : one.label }}
                    </td>
                  </div>
                </tr>

                <tr
                  style="text-align: left; line-height: 1.5"
                  v-for="(item, indexs) in pageGoods"
                  :key="indexs"
                  :style="{
                    fontSize:
                      main_settings.goodsSetData.fontset.fontSize + 'px',
                    fontWeight: main_settings.goodsSetData.fontset.bold
                      ? 'bold'
                      : 'none',
                    textDecoration: main_settings.goodsSetData.fontset.underline
                      ? 'underline'
                      : 'none',
                    fontStyle: main_settings.goodsSetData.fontset.italic
                      ? 'italic'
                      : 'none',
                    textAlign: main_settings.goodsSetData.fontset.textAlign,
                  }"
                >
                  <div
                    v-if="
                      tem_id == 9 &&
                      print_settings.printSetting.doublePrinting == 1
                    "
                  >
                    <div
                      v-if="
                        Object.keys(pageGoods).length >=
                        (item[0] - pageGoodsIndex * lineNumber) * 2
                      "
                    >
                      <td
                        v-for="(father, index) in main_settings.goodsSetData
                          .goodslist"
                        :key="index"
                        style="border: 1px solid #000; border-top: 0"
                      >
                        <div v-if="showPageHeader">
                          {{
                            pageGoods[
                              (item[0] * 2 -
                                1 -
                                1 -
                                pageGoodsIndex * lineNumber) %
                                lineNumber
                            ] &&
                            pageGoods[
                              (item[0] * 2 -
                                1 -
                                1 -
                                pageGoodsIndex * lineNumber) %
                                lineNumber
                            ][1]
                              ? pageGoods[
                                  (item[0] * 2 -
                                    1 -
                                    1 -
                                    pageGoodsIndex * lineNumber) %
                                    lineNumber
                                ][`${father.index - 1}`]
                              : ""
                          }}
                        </div>
                        <div v-else>
                          {{
                            pageGoods[
                              item[0] * 2 - 1 - pageGoodsIndex * lineNumber
                            ][1]
                              ? pageGoods[
                                  item[0] * 2 - 1 - pageGoodsIndex * lineNumber
                                ][`${father.index - 1}`]
                              : ""
                          }}
                        </div>
                      </td>

                      <td
                        v-for="(fathers, index) in main_settings.goodsSetData
                          .goodslist"
                        :key="index + '1'"
                        style="
                          border: 1px solid #000;
                          border-top: 0;
                          height: 30px;
                        "
                      >
                        <div v-if="showPageHeader">
                          {{
                            (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                              lineNumber !=
                              0 &&
                            pageGoods[
                              (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                                lineNumber
                            ] &&
                            pageGoods[
                              (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                                lineNumber
                            ][1]
                              ? pageGoods[
                                  (item[0] * 2 -
                                    1 -
                                    pageGoodsIndex * lineNumber) %
                                    lineNumber
                                ][`${fathers.index - 1}`]
                              : ""
                          }}
                        </div>

                        <div v-else>
                          {{
                            pageGoods[
                              item[0] * 2 - pageGoodsIndex * lineNumber
                            ][1]
                              ? pageGoods[
                                  item[0] * 2 - pageGoodsIndex * lineNumber
                                ][`${fathers.index - 1}`]
                              : ""
                          }}
                        </div>
                      </td>
                    </div>
                  </div>

                  <div v-else>
                    <td
                      v-for="(its, index) in main_settings.goodsSetData
                        .goodslist"
                      :key="index"
                      style="border: 1px solid #000; border-top: 0"
                    >
                      {{ item[`${its.index - 1}`] }}
                    </td>
                  </div>
                </tr>
              </tbody>
            </table>
          </div>

          <div style="clear: both"></div>
          <!-- 合计 -->
          <div class="count">
            <table
              v-if="main_settings.countSetData.countlist.length > 0"
              style="
                width: 100%;
                margin: 0;
                padding: 0;
                border: 1px solid #000;
                border-bottom: 0;
                border-top: 0;
                border-spacing: 0;
                border-collapse: collapse;
              "
            >
              <tbody>
                <tr style="text-align: left; height: 25px; line-height: 25px">
                  <td
                    style="border: 1px solid #000; border-top: 0"
                    v-for="(item, index) in main_settings.countSetData
                      .countlist"
                    :key="index"
                    :style="{
                      Width: item.width + 'px',
                      fontSize:
                        main_settings.countSetData.fontset.fontSize + 'px',
                      fontWeight: main_settings.countSetData.fontset.bold
                        ? 'bold'
                        : 'none',
                      textDecoration: main_settings.countSetData.fontset
                        .underline
                        ? 'underline'
                        : 'none',
                      fontStyle: main_settings.countSetData.fontset.italic
                        ? 'italic'
                        : 'none',
                      borderLeft: index != 0 ? '0' : '1px solid #000',
                    }"
                  >
                    <div
                      v-if="item.index == 4 && showPageHeader && tem_id == 9"
                    >
                      {{ item.label }}:{{ pageGoods.total }}
                    </div>
                    <div v-else-if="item.index > 4 && tem_id == 9">
                      {{ item.label }}:{{ all[`${item.index - 2}`] }}
                    </div>
                    <div v-else>
                      {{ item.label }}:{{ all[`${item.index - 1}`] }}
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div
            class="sign"
            style="height: 60px; width: 100%; position: absolute; clear: both"
            :style="{
              left: main_settings.mainSetData.mainlist.signlist.left + 'px',
            }"
          >
            <span
              v-for="(item, index) in main_settings.signSetData.signlist"
              :key="index"
              style="
                position: absolute;
                overflow: hidden;
                z-index: 1;
                letter-spacing: 1px;
              "
              :style="{
                left: item.left + 'px',
                top: item.top + 'px',
                fontSize: main_settings.signSetData.fontset.fontSize + 'px',
                fontWeight: main_settings.signSetData.fontset.bold
                  ? 'bold'
                  : 'none',
                textDecoration: main_settings.signSetData.fontset.underline
                  ? 'underline'
                  : 'none',
                fontStyle: main_settings.signSetData.fontset.italic
                  ? 'italic'
                  : 'none',
              }"
            >
              <span v-if="item.custom">{{ item.label }}</span>
              <span v-else>{{ item.label | remove }}</span>
            </span>
          </div>

          <p
            v-if="showPageHeader"
            style="font-size: 14px; text-align: center; margin-top: 60px"
          >
            第{{ pageGoodsIndex + 1 }}页，共{{ order_list.length }}页
          </p>

          <div :style="{ marginBottom: topMargin + 'px' }"></div>
        </div>
      </template>
    </div>

    <!-- <div id="left" v-if="print_settings.printSetting.isLeftTurn90==true">

    </div> -->
  </div>
</template>

<script>
import { getLodop } from "@/utils/LodopFuncs";
import {
  order_print,
  orderPrint,
  historyPrint,
  purchase_print,
  purchase_return_print,
  sort_print,
  statement_print,
  account_list_print,
  advice_list_print,
  sort_user_print,
  cash_delivery_order_print, //货到付款账单---订单
  online_payment_order_print, //在线支付账单---订单
  order_return_print, //订单退货单
  storage_print, //入库单打印
  stockout_print, // 出库单打印
} from "@/api/order/orderList";
import { batch_unbind_print, printEmpty } from "@/api/financial/finaicalOther";
import { get_print_mark } from "@/api/global/globalPrint";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { mapGetters } from "vuex";
import QRCode from "qrcodejs2";

export default {
  data() {
    return {
      a: "center",
      id: "",
      show: false,
      print_document_type: "", //打印的表单类型
      // 配送大写
      all: [],
      // 模板数据
      main_settings: {
        countSetData: {
          countlist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center",
          },
        },
        goodsSetData: {
          goodslist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center",
          },
        },
        mainSetData: {
          mainlist: {
            countlist: {},
            signlist: {},
            goodslist: {},
            orderlist: {},
          },
        },
        orderSetData: {
          orderlist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center",
          },
        },
        signSetData: {
          signlist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center",
          },
        },
      },
      // 商品表单处理过的数据
      sortgoods: [],
      print_settings: {
        page: {},
        printSetting: {
          is_category: false,
          doublePrinting: "",
        },
        fontset: {
          fontSize: "14",
          bold: false,
          underline: "false",
          italic: false,
          textAlign: "center",
        },
      },
      order: "",
      order_list: "",
      category_list: [], //分类

      // 打印机配置信息
      print_set_info: [],
      // 是否连续打印
      continuous: false,
      // 预览
      preview: false,
      // 分页打印
      lineNumber: 0,
      topMargin: 10,
      // 是否分页打印
      showPageHeader: false,
      tem_id: "",
      newtablist: [],
      total: "",
    };
  },
  computed: {
    ...mapGetters(["avatar"]),
    print_setting() {
      return `print_setting_list_${this.avatar.company_id}`;
    },
  },
  filters: {
    remove: function (data) {
      if (data.indexOf("：") != -1 || data.indexOf(":") != -1) {
        return data;
      } else {
        return data + ":";
      }
    },
  },
  mounted() {
    this.monitoring(); // 注册监听事件
  },
  created() {
    // this.getTemplateData({ id: 1407, type: "order", uid: 339 });
  },
  methods: {
    democc(data) {
      if (data.category_name) {
        return false;
      } else {
        return true;
      }
    },
    monitoring() {
      // 监听事件
      this.$on("demo", async (res) => {
        this.get_print_info();
        await this.getTemplateData(res);
        if(res.cd) {
          res.cd(res.id);
        }
      });
    },
    // 获取打印机配置信息
    get_print_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      let print_setting_list = localStorage.getItem(this.print_setting);
      if (print_setting_list) {
        try {
          this.print_set_info = JSON.parse(print_setting_list);
        } catch (error) {
          console.log(error);
        }
      }
      // get_print_mark(data).then((res) => {
      // 	if (res.errcode == 0) {
      // 		this.print_set_info = res.data.list;
      // 	}
      // });
    },
    // 数组分割
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      let suLength = Number(subGroupLength);
      if (this.showPageHeader) {
        if (Array.isArray(array)) {
          while (index < array.length) {
            newArray.push(array.slice(index, (index += suLength)));
          }
        } else {
          let arr = Object.values(array) ? Object.values(array) : [];
          while (index < arr.length) {
            newArray.push(arr.slice(index, (index += suLength)));
          }
        }
      } else {
        newArray = [array];
      }
      if (this.showPageHeader && this.tem_id == 9) {
        newArray.map((e) => {
          e.total = 0;
          let total = 0;
          e.map((c) => {
            total += Number(c[9]) || 0;
          });
          e.total = this.$toFixed(total);
        });
      }
      return newArray;
    },
    // 处理分类数据
    handleCategory(array) {
      let newArray = [];
      array.map((e) => {
        let values = Object.values(e.list) ? Object.values(e.list) : [];
        values.map(async (i) => await newArray.push(i));
        let obj = {
          category_name: e.category_name,
          class: e.class,
          money: e.money,
        };
        newArray.push(obj);
      });
      return this.group(newArray, this.lineNumber);
    },
    // 加载数据
    getTemplateData(res) {
      return new Promise((resolve, reject) => {
        let id = res.id;
        let uid = res.uid;
        let nickname = res.nickname;
        this.print_document_type = res.type;
        let type = res.type;
        this.continuous = res.continuous;
        this.preview = res.preview;
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          { id: id, uid: uid, nickname: nickname }
        );
        if (res.type == "sortuser") {
          data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            { oid: id, sort_rule: res.sort_rule }
          );
        }
        // 获取数据函数
        let getFunc = "";
        switch (type) {
          case "order":
            getFunc = order_print;
            break;
          case "orderPrint": 
            getFunc = orderPrint;
            break;
          case "historyPrint":
            getFunc = historyPrint;
            break;
          case "purchase":
            getFunc = purchase_print;
            break;
          case "purchase_return":
            getFunc = purchase_return_print;
            break;
          case "sort":
            getFunc = sort_print;
            break;
          case "receivables":
            getFunc = statement_print;
            break;
          case "account":
            getFunc = account_list_print;
            break;
          case "advice":
            // 采购结算
            getFunc = advice_list_print;
            break;
          case "sortuser":
            getFunc = sort_user_print;
            break;
          case "cash_delivery_order":
            getFunc = cash_delivery_order_print;
            break;
          case "online_payment_order":
            getFunc = online_payment_order_print;
            break;
          case "order_return":
            getFunc = order_return_print;
            break;
          case "other_user_order":
            getFunc = batch_unbind_print;
            break;
          case "other_user_completed_order":
            getFunc = printEmpty;
            break;
          case "storage":
            getFunc = storage_print;
            break;
          case "stockout":
            getFunc = stockout_print;
            break;
        }
        getFunc(data).then((res) => {
          if(res.errcode == 0) {
            this.all = res.list.all;
            this.main_settings = JSON.parse(res.list.mubang.main_settings);
            this.print_settings = JSON.parse(res.list.mubang.print_settings);
            this.lineNumber = this.print_settings.printSetting.lineNumber || 10;
            this.showPageHeader = this.print_settings.printSetting.showPageHeader;
            let topMargin = this.print_settings.printSetting.topMargin;
            this.topMargin = Number(topMargin) + 40;
            this.order = res.list.order;
            this.order_list = [];
            this.tem_id = res.list.mubang.tem_id;
            if ((type == "order" || type=="orderPrint" || type=="historyPrint") && this.print_settings.printSetting.is_category) {
              let arr = [];
              res.list.order_list1.map((e) => {
                arr.push({
                  category_name: e.category_name,
                  class: e.class,
                  money: e.money,
                });
              });
              this.category_list = arr;
              this.order_list = this.handleCategory(res.list.order_list1);
            } else {
              if (
                this.tem_id == 9 &&
                this.print_settings.printSetting.doublePrinting == 1
              ) {
                this.newtablist = this.main_settings.goodsSetData.goodslist;
                let len = Object.keys(res.list.order_list).length;
  
                if (this.showPageHeader == true) {
                  //开启双排和分页
                  if (len % 2 == 0) {
                    this.order_list = this.group(
                      res.list.order_list,
                      this.lineNumber
                    );
                  } else {
                    let arr = res.list.order_list;
                    let newlist = arr[1];
                    const arr2 = new Array(newlist.length).fill(null);
                    arr2[0] = len + 1;
                    let key = len + 1;
                    let value = arr2;
                    arr[key] = value;
                    this.order_list = this.group(
                      res.list.order_list,
                      this.lineNumber
                    );
                  }
                } else {
                  //只开启双排
                  if (len % 2 == 0) {
                    this.order_list = this.group(
                      res.list.order_list,
                      this.lineNumber
                    );
                  } else {
                    let arr = res.list.order_list;
                    let newlist = arr[1];
                    const arr2 = new Array(newlist.length).fill(null);
                    arr2[0] = len + 1;
                    let key = len + 1;
                    let value = arr2;
                    arr[key] = value;
                    this.order_list = this.group(
                      res.list.order_list,
                      this.lineNumber
                    );
                  }
                }
              } else {
                this.order_list = this.group(
                  res.list.order_list,
                  this.lineNumber
                );
              }
            }
  
            this.main_settings.goodsSetData.goodslist = this.calc(
              this.main_settings.goodsSetData.goodslist
            );
            this.main_settings.countSetData.countlist = this.calc(
              this.main_settings.countSetData.countlist
            );
            this.show = true;
  
            this.print_set_info.map((item) => {
              if (item.type == res.list.mubang.tem_id) {
                this.print_settings.print_mark = item.print_index;
              }
            });
            this.$nextTick(() => {
              this.generateQRCode(res.list.qrCodeUrl, 80, 80)
                .then(() => {
                  // 二维码生成完成后执行打印操作
                  this.print(this.print_settings);
                  resolve()
                })
                .catch((error) => {
                  this.print(this.print_settings);
                  resolve()
                });
            });
          }else {
            this.$message.error(res.errmsg);
            resolve();
          }
        });
      });
    },
    // 生成二维码
    generateQRCode(url, width, height) {
      return new Promise((resolve, reject) => {
        let qrcode = new QRCode("qrcode", {
          width: width,
          height: height,
          text: url,
        });
        // 等待100毫秒以确保二维码已经生成
        setTimeout(() => {
          resolve();
        }, 100);
      });
    },
    // 计算每个元素的宽度
    calc(array) {
      function sortData(a, b) {
        return a.left - b.left;
      }
      let newarr = array.sort(sortData);

      let widthall = 0;
      for (let i = 0; i < newarr.length; i++) {
        if (newarr[i].label == "序号") {
          newarr[i].width = 40;
        } else if (i == 0) {
          newarr[i].width = newarr[i].left + 70;
        } else {
          newarr[i].width = newarr[i].left - newarr[i - 1].left;
        }
        widthall += newarr[i].width;
      }
      newarr.map((e) => {
        e.percent = Math.round((e.width / widthall) * 100);
      });
      // console.log(newarr,'new')
      return newarr;
    },
    // 订单打印事件
    print(params) {
      console.log(params, getLodop());
      let LODOP = getLodop();
      if (!LODOP) {
        return;
      }
      if (params.print_mark != -1) {
        LODOP.SET_PRINTER_INDEX(params.print_mark);
      }
      LODOP.SET_PRINT_PAGESIZE(
        1,
        params.page.width + "mm",
        params.page.height + "mm",
        params.page.headerTitle
      );
      LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW", true); //设置页面缩放

      let isLeftTurn = this.print_settings.printSetting.isLeftTurn90;

      if (this.tem_id == 9 && isLeftTurn == true) {
        LODOP.ADD_PRINT_HTM(
          params.printSetting.topMargin + "px",
          params.printSetting.leftMargin + "px",
          "52%",
          "100%",
          document.getElementById("main").innerHTML
        );
        LODOP.SET_PRINT_STYLEA(0, "AngleOfPageInside", 90);
      } else {
        LODOP.SET_PRINT_STYLEA(0, "Vorient", 0);
        LODOP.ADD_PRINT_HTM(
          params.printSetting.topMargin + "px",
          params.printSetting.leftMargin + "px",
          "100%",
          "100%",
          document.getElementById("main").innerHTML
        );
      }

      if ((params.printSetting.isShow && !this.continuous) || this.preview) {
        LODOP.PREVIEW();
      } else {
        LODOP.PRINT();
      }
      this.$nextTick(()=>{
        if(document.getElementById("qrcode")){
          // 清空二维码
          document.getElementById("qrcode").innerHTML = "";
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped></style>
